import requests
from PIL import Image
from io import BytesIO
import time

url = 'https://api-inference.modelscope.cn/v1/images/generations'
payload = {
    'model': 'bylander/woodcutprint_v4',
    'prompt': 'woodcut print,black and white,An owl standing on a tree trunk,woodcut print',
    'n': 1,
    'size': '1024x1024'
}
headers = {
    'Authorization': 'Bearer ms-04c601b8-2489-4b24-931e-28454f47b8fc',
    'Content-Type': 'application/json'
}

# 发送请求（含重试逻辑）
for _ in range(3):  # 最多重试3次
    print(1)
    response = requests.post(url, json=payload, headers=headers)
    print(2)
    response_data = response.json()
    print("API响应:", response_data)
    
    if 'images' in response_data and response_data['images']:
        try:
            image_url = response_data['images'][0]['url']
            img_data = requests.get(image_url, timeout=10).content
            image = Image.open(BytesIO(img_data)).convert('RGB')
            image.save('result_image.jpg')
            print("图片保存成功！")
            break
        except Exception as e:
            print(f"图片处理失败: {e}")
            time.sleep(2)  # 等待2秒后重试
    else:
        print("生成失败，错误详情:", response_data.get('error', '未知错误'))
